﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;


namespace MyQQ
{
    class DataOperator
    {
        //连接数据库，"Data Source = 服务器名; Initial Catalog = db_MyQQ; Integrated Security = SSPI"，
        //如果用sqlServer验证登录方式有问题，就用windows验证方式，复制下方代码，只需要修改服务器名即可
        private static string connString = "Data Source = LAPTOP-FFNS7H5V\\NEWSQL; Initial Catalog = db_MyQQ; Integrated Security = SSPI";
        public static SqlConnection connection = new SqlConnection(connString);
        //定义方法执行SQL语句，返回结果中的第一列第一行
        public int ExecSQL(string sql)
        {
            SqlCommand command = new SqlCommand(sql, connection);//指定要执行的SQL语句
            if (connection.State == ConnectionState.Closed)      //如果当前数据库链接属于关闭状态
                connection.Open();                               //打开数据连接
            int num = Convert.ToInt32(command.ExecuteScalar());  //执行查询
            connection.Close();                                  //关闭数据库查询
            return num;                                          //返回结果中的第一列第一行
        }
        //返回受影响的行数
        public int ExecSQLResult(string sql)
        {
            SqlCommand command = new SqlCommand(sql, connection);
            if (connection.State == ConnectionState.Closed)
                connection.Open();
            int result = command.ExecuteNonQuery();
            connection.Close();
            return result;
        }
        //从数据库获取用户和好友的相关信息
        public SqlDataReader GetDataReader(string sql)
        {
            SqlCommand command = new SqlCommand(sql,connection);
            if (connection.State == ConnectionState.Open)
                connection.Close();
                connection.Open();
                SqlDataReader datareader = command.ExecuteReader();
                return datareader;
        }
        //执行SQL查询语句，返回DataSet数据集
        public DataSet GetDataSet(string sql)
        {
            SqlDataAdapter sqlda = new SqlDataAdapter(sql, connection);
            DataSet ds = new DataSet();                            //创建数据集对象
            sqlda.Fill(ds);                                        //填充数据集
            return ds;                                             //返回数据集
        }
    }
}


